package com.scalar.chiptrack.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class ExecuteUtils
{


    static public String[] runCommand(String cmd) throws IOException
    {
        // The actual procedure for process execution: runCommand( String cmd);
        ArrayList list = new ArrayList(); // Create a list for storing output.
        Process proc = Runtime.getRuntime().exec(cmd); // Executea command and get its process handle
        InputStream istr = proc.getInputStream(); // Get thehandle for the processes [InputStream]
        BufferedReader br = new BufferedReader(new InputStreamReader(istr));
        // Create a [BufferedReader] and specify it reads from an input stream.

        String str; // Temporary String variable
        while ((str = br.readLine()) != null)
            list.add(str);
            // Read to Temp Variable, Check for [null] then Add to (ArrayList)list

            try {
                proc.waitFor();
            } // Wait for process to terminate and catch any Exceptions.
            catch (InterruptedException e){
                System.err.println("Process was interrupted");
            }

            // Note: proc.exitValue() returns the exit value. (Use ifrequired)

            br.close(); // Done.

            return (String[])list.toArray(new String[0]); // Convert the list to a string and return
    }

    public static void main(String args[]) throws IOException //Actual execution starts here
    {
        try
        {
            //String outlist[] = runCommand(args[0]); // Run and get the output.
            String outlist[] = runCommand("D:/chiptrac_cavium/exe/ConvertCSV.exe C:\\temp\\temp\\ose\\pixelworks\\PCCWIP040606.xls");
            for (int i = 0; i < outlist.length; i++)
                    System.out.println(outlist[i]);
            // Print the output to screen character by character.
            // Safe and not very inefficient.
        }
        catch (IOException e) { System.err.println(e); }
        }
    }